package com.yiren.dbaa.module.practice_set.map.model;

import android.app.Activity;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.yiren.backstage.currency.entity.LineInfoEntity;
import com.yiren.backstage.currency.entity.MapEntity;
import com.yiren.backstage.currency.utils.FileUtil;
import com.yiren.dbaa.constant.AddressConstant;
import com.yiren.dbaa.currency.api.CommonCallBack;
import com.yiren.dbaa.module.practice_set.map.contract.MapHomeContract;
import com.yiren.dbaa.net.OkHttpUtils;
import com.yiren.dbaa.net.bean.BaseResponseBean;
import com.yiren.dbaa.net.bean.OSSResultBean;
import com.yiren.dbaa.net.bean.TestBaseBean;
import com.yiren.dbaa.net.interf.OssFileCallback;
import com.yiren.dbaa.net.interf.StringCallback;
import com.yiren.dbaa.net.oss.IOssFileOperationApi;
import com.yiren.dbaa.net.oss.impl.OssFileOperationApiImpl;
import com.yiren.dbaa.util.ZipUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * @author lwb
 * @date : 2022/11/24 14:41
 * @description: 地图首页
 */
public class MapHomeModel implements MapHomeContract.Model {

    private Activity activity;
    private IOssFileOperationApi iOssFileOperationApi;
    private Gson gson;

    public MapHomeModel(Activity activity) {
        this.activity = activity;
        gson = new Gson();
    }

    @Override
    public void getMapFromServer(String id, boolean isPublic, CommonCallBack callBack) {
        OkHttpUtils.getInstance().getStringByAsync(activity, AddressConstant.loadMapByUser("?userId=" + id), new StringCallback() {
            @Override
            public void getString(String result) {
                TestBaseBean<List<MapEntity>> testBaseBean = gson.fromJson(result, new TypeToken<TestBaseBean<List<MapEntity>>>() {
                }.getType());
                if (testBaseBean.isSuccess()) {
                    if (testBaseBean.getData() != null && !isPublic) {
                        List<MapEntity> mapList = new ArrayList<>();
                        for (int i = 0; i < testBaseBean.getData().size(); i++) {
                            if (testBaseBean.getData().get(i).getState() == 1) {
                                mapList.add(testBaseBean.getData().get(i));
                            }
                        }
                        callBack.success(mapList);
                    } else {
                        callBack.success(testBaseBean.getData());
                    }
                } else {
                    callBack.fail("数据请求错误!");
                }
            }

            @Override
            public void getFail() {
                callBack.fail("数据请求失败!");
            }
        });
    }

    @Override
    public List<MapEntity> lineHomeDataMerge(List<MapEntity> localMaps, List<MapEntity> serverMaps) {
        for (MapEntity localMap : localMaps) {
            boolean exist = false;
            for (int i = 0; i < serverMaps.size(); i++) {
                MapEntity serverMap = serverMaps.get(i);
                //本地存在 以本地数据为准
                if (localMap.getId().equals(serverMap.getId())) {
                    if (localMap.getMapVer() > 0)
                        localMap.setMapVerLast(serverMap.getMapVer());
                    //判断版本是否可更新
                    if (localMap.getMapVer() < serverMap.getMapVer()) {
                        localMap.setUpdateDetails(serverMap.getUpdateDetails());
                        localMap.setUpdate(true);
                    }
                    //判断本地文件是否存在
                    if (localMap.getMapVer() >= 0)
                        localMap.setDownLoad(true);
                    serverMaps.set(i, localMap);
                    exist = true;
                    break;
                }
            }
            //新增
            if (!exist) {
                localMap.setDownLoad(true);
                serverMaps.add(localMap);
            }
        }
        return serverMaps;
    }

    @Override
    public void downloadSiteMap(String siteCode, int partnerId, float version, CommonCallBack callBack) {
        String objectKey = partnerId + "/" + siteCode + "/" + version + ".zip";
        String mapFileDir = AddressConstant.App_Main_Directory() + partnerId + "/map";
        File file = new File(mapFileDir);
        if (!file.exists()) file.mkdir();
        String sdkDownDir = mapFileDir + "/" + siteCode;
        String sdkDownUrl = sdkDownDir + "/";
        String fileName = version + ".zip";
        iOssFileOperationApi = new OssFileOperationApiImpl(activity);
        iOssFileOperationApi.downLoadFile(AddressConstant.DJ_PUBLIC_DATA, objectKey, sdkDownUrl, fileName, new OssFileCallback() {
            @Override
            public void success(String result) {
                try {
                    //删除file中除文件名为fileName的所有文件
                    File file = new File(sdkDownDir);
                    FileUtil.deleteFile(file, fileName);
                    //解压fileName
                    File pressFile = new File(sdkDownUrl, fileName);
                    ZipUtils.decompressFile(pressFile, sdkDownUrl);
                    //删除 zip 文件
                    pressFile.delete();
                    callBack.success(result);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void fail(String error) {
                callBack.fail(error);
            }
        });
    }

    @Override
    public void getDataDirAuth(CommonCallBack callBack) {
        OkHttpUtils.getInstance().getStringByAsync(activity, AddressConstant.getDataDirAuthv3("?dataType=km3_traject"), new StringCallback() {
            @Override
            public void getString(String result) {
                BaseResponseBean<OSSResultBean> responseBean = gson.fromJson(result, new TypeToken<BaseResponseBean<OSSResultBean>>() {
                }.getType());
                if (responseBean.getError() != null) {
                    callBack.fail(responseBean.getError().getMessage());
                } else {
                    callBack.success(responseBean.getResult());
                }
            }

            @Override
            public void getFail() {
                callBack.fail("获取数据目录授权失败！");
            }
        });
    }

    @Override
    public void uploadSiteMap(OSSResultBean ossResultBean, int userId, String siteCode, String zipFileName, String dataZipFile, CommonCallBack callBack) {
        iOssFileOperationApi = new OssFileOperationApiImpl(activity);
        String objectKey = userId + "/" + siteCode + "/" + zipFileName;
        iOssFileOperationApi.uploadFile(AddressConstant.DJ_PUBLIC_DATA, objectKey, dataZipFile, new OssFileCallback() {
            @Override
            public void success(String result) {
                callBack.success("");
            }

            @Override
            public void fail(String error) {
                callBack.fail(error);
            }
        });
    }
}
